import 'package:flutter/material.dart';
import 'post.dart';
 
class DataTableSortPost extends StatefulWidget {
  @override
  _DataTableSortPostState createState() => _DataTableSortPostState();
}
 
class _DataTableSortPostState extends State<DataTableSortPost> {
  int _sortColumnIndex = 0;
  bool _sortAscending = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DataTableDemo'),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: ListView(
          children: <Widget>[
            DataTable(
                // 排序的列 0的话就是第一列
                sortColumnIndex: _sortColumnIndex,
                //true 升序 false 降序
                sortAscending: _sortAscending,
                columns: [
                  DataColumn(
                      label: Text("Title"),
                      onSort: (int index, bool ascending) {
                        setState(() {
                          _sortColumnIndex = index;
                          _sortAscending = ascending;
                          posts.sort(
                            (a,b){
                              if(!ascending){
                                final c=a;
                                a=b;
                                b=c;
                              }
                              // 按照标题内容的长度排序
                              return a.title.length.compareTo(b.title.length);
                            }
                          );
                        });
                      }),
                  DataColumn(label: Text('Anthor')),
                  DataColumn(label: Text('Image')),
                ],
                rows: posts.map((post) {
                  return DataRow(cells: [
                    DataCell(Text(post.title)),
                    DataCell(Text(post.author)),
                    DataCell(Image.network(post.imgeUrl)),
                  ]);
                }).toList()),
          ],
        ),
      ),
    );
  }
}
